import {
  eventHandler,
  readBody,
  getMethod,
  getRouterParam,
  createError,
} from "h3";

// 模拟商品数据存储 (实际项目中这应该是共享的数据层)
let products = [
  {
    id: 1,
    name: "iPhone 15",
    price: 7999,
    description: "最新款苹果手机",
    category: "电子产品",
    stock: 50,
    createTime: new Date("2024-01-01").toISOString(),
    updateTime: new Date("2024-01-01").toISOString(),
  },
  {
    id: 2,
    name: "MacBook Pro",
    price: 15999,
    description: "高性能笔记本电脑",
    category: "电子产品",
    stock: 30,
    createTime: new Date("2024-01-02").toISOString(),
    updateTime: new Date("2024-01-02").toISOString(),
  },
  {
    id: 3,
    name: "Nike运动鞋",
    price: 899,
    description: "舒适透气运动鞋",
    category: "服饰",
    stock: 100,
    createTime: new Date("2024-01-03").toISOString(),
    updateTime: new Date("2024-01-03").toISOString(),
  },
];

export default eventHandler(async (event) => {
  const method = getMethod(event);
  const productId = parseInt(getRouterParam(event, "id") || "0");

  if (!productId) {
    throw createError({
      statusCode: 400,
      statusMessage: "商品ID无效",
    });
  }

  // GET /api/products/[id] - 获取单个商品
  if (method === "GET") {
    const product = products.find((p) => p.id === productId);

    if (!product) {
      throw createError({
        statusCode: 404,
        statusMessage: "商品不存在",
      });
    }

    return {
      success: true,
      data: product,
    };
  }

  // PUT /api/products/[id] - 更新商品
  if (method === "PUT") {
    const body = await readBody(event);
    const productIndex = products.findIndex((p) => p.id === productId);

    if (productIndex === -1) {
      throw createError({
        statusCode: 404,
        statusMessage: "商品不存在",
      });
    }

    // 验证必填字段
    if (body.name && !body.name.trim()) {
      throw createError({
        statusCode: 400,
        statusMessage: "商品名称不能为空",
      });
    }

    if (
      body.price !== undefined &&
      (isNaN(Number(body.price)) || Number(body.price) < 0)
    ) {
      throw createError({
        statusCode: 400,
        statusMessage: "价格必须是有效的正数",
      });
    }

    // 更新商品信息
    const updatedProduct = {
      ...products[productIndex],
      ...body,
      id: productId, // 确保ID不会被覆盖
      price:
        body.price !== undefined
          ? Number(body.price)
          : products[productIndex].price,
      stock:
        body.stock !== undefined
          ? Number(body.stock)
          : products[productIndex].stock,
      updateTime: new Date().toISOString(),
    };

    products[productIndex] = updatedProduct;

    return {
      success: true,
      data: updatedProduct,
      message: "商品更新成功",
    };
  }

  // DELETE /api/products/[id] - 删除商品
  if (method === "DELETE") {
    const productIndex = products.findIndex((p) => p.id === productId);

    if (productIndex === -1) {
      throw createError({
        statusCode: 404,
        statusMessage: "商品不存在",
      });
    }

    const deletedProduct = products[productIndex];
    products.splice(productIndex, 1);

    return {
      success: true,
      data: deletedProduct,
      message: "商品删除成功",
    };
  }

  // 不支持的HTTP方法
  throw createError({
    statusCode: 405,
    statusMessage: "Method Not Allowed",
  });
});
